<?php
class CARXTable  extends DataBase
{
	var $m_tables;
	var $m_filter;
	var $m_start;
	var $m_rows;
	var $m_fieldNames;
	var $m_order;
	var $m_groupBy;
	var $m_sql;
	var $m_fields;
	var $m_lastError;
	/**
         *  Array of field names which must be not quoted
         *  (e.g NOW() should not be quoted)
         */

	var $m_notQuoteFields;

	var $m_mysql_result;
	var $m_rowNum;

	var $m_insert_id;

	var $m_lastSQL;

	var $m_joinedTable; // Таблица, которую присоединяем
	var $m_joinCondition; //t1.id=t2.id условие для ON
	var $m_joinTableFields; //поля, которые вытаскиваем из приджогиваемой таблицы

	function CARXTable($tables = "", $filter = "", $fieldNames = "*", $start = 0, $rows = -1, $order = "", $groupBy = "")
	{
		parent::DataBase();
		$this->m_sql = "";
		//$this->m_tables = $tables;

		if (substr_count($tables,ARX_DB_TABLE_PREFIX))
		{
			$this->m_tables = $tables;
		}
		else
		{
			$this->m_tables=ARX_DB_TABLE_PREFIX.$tables;
		}


		$this->m_filter = $filter;
		$this->m_fieldNames = $fieldNames;
		$this->m_start = $start;
		$this->m_rows = $rows;
		$this->m_fields = NULL; //результат запроса в виде массива
		$this->m_notQuoteFields = array(); //значения, которые при вставке не надо заключать в одинарные кавычки
		$this->m_rowNum = 0; //количество рядов, которые получены в результате sql-запроса
		$this->m_order = $order;
		$this->m_groupBy = $groupBy;
		$this->m_insert_id = 0;
	}


	function SetFilter($filter)
	{
		$this->m_filter = $filter;
	}

	function joinTable($joinTableName,$joinCondition,$joinTableFields)
	{
		$this->m_joinedTable=$joinTableName;
		$this->m_joinCondition=$joinCondition;
		$this->m_joinTableFields=$joinTableFields;
	}

	function SetOrder($order)
	{
		$this->m_order = $order;
	}

	function SetGroup($group)
	{
		$this->m_groupBy=$group;
	}

	function SetLimits($start = 0, $rows = -1)
	{
		$this->m_start = $start;
		$this->m_rows = $rows;
	}

	function SetSQL($sql)
	{
		$this->m_sql = $sql;
	}

	function Open($sql = "")
	{
		if (!$sql && $this->m_sql)
		{
			$sql = $this->m_sql;
		}

		if (!$sql)
		{
			if ($this->m_joinedTable)
			{
				$mainTableAlias=' t1';
				$sqlJoin=" LEFT JOIN {$this->m_joinedTable} t2 ON {$this->m_joinCondition} ";
				$tmpFld = explode(',',$this->m_fieldNames);
				//временная хуйня. потом переписать по-нормальномк надо будет!!!
				foreach ($tmpFld as $k=>$v)
				{
					if (!substr_count($v,'distinct') && !substr_count($v,'unixtime') && !substr_count($v,'DATE_FORMAT'))
					{
						$tmpFld[$k]='t1.'.$v;
					}
					elseif (substr_count($v,'distinct'))
					{
						$v=str_replace('distinct','',$v);
						$tmpFld[$k]='distinct t1.'.$v;
					}
				}
				/////////////////////////////////////////////////////////////////////
				$joinFld=explode(",",$this->m_joinTableFields);
				foreach ($joinFld as $k=>$v)
				{
					$joinFldStr.=",t2.$v";

				}
				$this->m_fieldNames=implode(",",$tmpFld).$joinFldStr;
			}

			$tables=$this->m_tables.$mainTableAlias;

			$sql = "SELECT " . $this->m_fieldNames . " FROM " . $tables .$sqlJoin;

			if ($this->m_filter)
			{
				$sql .= " WHERE " . $this->m_filter;
			}

			if ($this->m_groupBy)
			{
				$sql .= " GROUP BY " . $this->m_groupBy;
			}

			if ($this->m_order)
			{
				$sql .= " ORDER BY " . $this->m_order;
			}


			if ($this->m_rows != -1)
			{
				$sql .= " LIMIT " . $this->m_start . ", " . $this->m_rows;

			}
			else if ($this->m_start != 0)
			{
				$sql .= " LIMITS " . $this->m_start;
			}
		}

		$this->m_lastSQL = $sql;

		$this->m_mysql_result = $this->Query($sql);

		if (!$this->m_mysql_result)
		{
			$this->m_lastError = mysql_error();
			//			echo "Database error: ".mysql_error()."\n<br>$sql";
		}

		$this->m_fields = $this->FetchArray($this->m_mysql_result);
		$this->m_rowNum = 0;
	}

	function Close()
	{
		$this->m_fields = NULL;
		if ($this->m_mysql_result)
		{
			@mysql_free_result($this->m_mysql_result);
		}
	}



	/**
         * Open table, return first row as associative array, close table.
         *
         * If no rows found, return NULL
         *
         * @author Alexey Korepanov <korepanov@ringo-web.ru>
         * @copyright RINGO-WEB 2004
         * @param int $varname description
         * @return array row
         */
	function FetchRow()
	{
		$this->Open();
		$result = $this->GetRow(); //GetRow возвращает m_fields (результат запроса в виде массива)
		$this->Close();
		return $result;
	}

	/**
         * return all rows as array
         *
         * if no rows was found, return NULL (?)<br>
         * ALTEX: add parameter $sql
         *
         * @author Alexey Korepanov <korepanov@ringo-web.ru>
         * @copyright RINGO-WEB 2004
         * @param string $sql sql to execute
         * @return array rows
         */
	function FetchRows($sql = '')
	{
		$result = array();
		$this->Open($sql);
		while ($rec = $this->GetRow())
		{
			$result[] = $rec;
			$this->Next();
		}
		$this->Close();
		return $result;
	}

	function Next()
	{
		$this->m_fields = $this->FetchArray($this->m_mysql_result);
		$this->m_rowNum++;
	}

	function GetRow()
	{
		if ($this->m_fields['c_usenick']==1 && !$this->usenickoff)
		{
			if (trim($this->m_fields['c_nick']))
			{
			$this->m_fields['c_name']=$this->m_fields['c_nick'];
			$this->m_fields['c_surname']='';
			$this->m_fields['c_nick']='';
			}
			
		}
		
		
		//print_r($this->m_fields);
		return $this->m_fields;
	}

	function GetRowNum()
	{
		return $this->m_rowNum;
	}

	function GetRowCount()
	{
		return @mysql_num_rows($this->m_mysql_result);
	}

	function ProcessDBRows($FnName, &$params)
	{

		if (function_exists($FnName))
		{
			$this->Open();
			$iRow = 0;
			while($fields = $this->GetRow())
			{
				$FnName($fields, $iRow, $params);
				$iRow++;
				$this->Next();
			}
			$this->Close();
		}
	}

	function SetField($field, $value, $bQuote = TRUE,$allowHtml=false,$addSlashes=true,$converToUtf=false)
	{
		//if (!$allowHtml) $value=htmlspecialchars($value);
		//if ($addSlashes) $value=addslashes($value);
		if ($converToUtf)
		{
			if (preg_match('//u', $value))
			$value=iconv("UTF-8", "WINDOWS-1251", urldecode($value));
		}
		if (!$bQuote) $this->m_notQuoteFields[$field] = TRUE;
		$this->m_fields[$field] = $value;
	}

	function GetField($field)
	{
		if (isset($this->m_fields[$field]))
		{
			return $this->m_fields[$field];
		}
		return NULL;
	}

	function Insert()
	{
		$tables=$this->m_tables;

		$sql = "INSERT INTO " . $tables . " \n";

		$firstField = TRUE;

		foreach ($this->m_fields as $name => $value)
		{
			if (!empty($name))
			{
				if (get_magic_quotes_gpc())
				{
					$value = stripslashes($value);
				}

				$value = stripslashes($value);

				$value = mysql_real_escape_string($value);

				if (!isset($this->m_notQuoteFields[$name]))
				{
					if ($value != 'NULL')
					{
						$value = "'$value'";
					}
				}

				if ($firstField)
				{
					$sql .= " SET \n";
					$sql .= " " . $name ."=". $value;
				}
				else
				{
					$sql .= ",\n " . $name . "=" . $value;
				}
				$firstField = FALSE;
			}
		}

		$this->m_lastSQL = $sql;
		$this->m_mysql_result = $this->Query($sql);

		if (!$this->m_mysql_result)
		{
			// ERROR TO LOG!!!
			$this->m_lastError = mysql_error();
			//			echo "Database error: ".mysql_error()."\n<br>$sql";
		}
		$this->m_insert_id = mysql_insert_id();
	}

	function RunSQL($sql)
	{
		$this->Query($sql);
	}

	function GetInsertId()
	{
		return $this->m_insert_id;
	}

	function Delete()
	{
		$tables=$this->m_tables;

		$sql = "DELETE FROM " . $tables . " \n";

		if ($this->m_filter)
		{
			$sql .= " WHERE " . $this->m_filter;
		}

		$this->m_lastSQL = $sql;

		$this->m_mysql_result = $this->Query($sql);

		if (!$this->m_mysql_result)
		{
			$this->m_lastError = mysql_error();
			// ERROR TO LOG!!!
			//			echo "Database error: ".mysql_error()."\n<br>$sql";
		}
	}

	function Update()
	{
		if ($this->m_fields)
		{
			//$tables = $this->GetTablesWithPrefixes(TRUE);
			$tables=$this->m_tables;

			$sql = "UPDATE " . $tables . " \n";

			$firstField = TRUE;
			foreach ($this->m_fields as $name => $value)
			{
				if (get_magic_quotes_gpc())
				{
					$value = stripslashes($value);
				}

				$value = stripslashes($value);

				$value = mysql_escape_string($value);

				if (!isset($this->m_notQuoteFields[$name]))
				{
					if ($value != 'NULL')
					{
						$value = "'$value'";
					}
				}

				if ($firstField)
				{
					$sql .= " SET \n";
					$sql .= " " . $name . " = " . $value;
				}
				else
				{
					$sql .= ",\n $name = $value";
				}
				$firstField = FALSE;
			}

			if ($this->m_filter)
			{
				$sql .= " WHERE $this->m_filter";
			}

			$this->m_lastSQL = $sql;
			$this->m_mysql_result = $this->Query($sql);

			if (!$this->m_mysql_result)
			{
				$this->m_lastError = mysql_error();
				// ERROR TO LOG!!!
				//				echo "Database error: ".mysql_error()."\n<br>$sql";
			}
		}
	}


}
?>